<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class arena extends Admin_Controller {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );
	var $model = "mgame";
	var $view = "game";
	var $resource = "";
    function __construct() {
        parent::__construct();
        $this->load->model($this->model);
        $this->load->model("mcategory");
        $this->load->model("mgame");
        $this->load->model("mgamecategory");
        $this->load->model("simage");
		$this->resCode = $this->{$this->model}->resCode;
		$this->resProcessCode = 'GAME_PROCESS';
        $this->url_index = admin_url() . $this->view;
        $this->folder_upload = "dataupload/".$this->view."/";
        $this->url_edit = $this->url_index . "/edit/";
        $this->url_delete = $this->url_index . "/delete/";
        $this->url_add = $this->url_index . "/edit/0";
		$this->url_search = $this->url_index . "/search";
		$this->resource = $this->mresource->get($this->resCode,'RES_CODE');
    }

    public function index($page = 0) {
		$this->check_permission();
        $data = array();
		$page = ($page <= 0) ? 1 : $page;
        $config = array();
        $config['per_page'] = 20;
        $config['cur_page'] = $page;
        $config['base_url'] = $this->url_index.'/index/';
		
		$this->search();
        $config['total_rows'] = $this->mgame->num();
        $this->pagination->initialize($config);
		$this->search();
		$this->db->order_by('game_id desc');
        $data['datas'] = $this->mgame->pagination('','',$config);
        $this->theme_data["main"] = $this->view."/index";
        $this->template->viewAdmin($this->theme_data, $data);
    }

    function edit($editID = 0) {
		$this->check_permission($editID);
		$this->load->model("mgameinstruction");
        $data = array();
        $post = $this->input->post();
        if ($post) {
			$post['edit']['user_id'] = $this->madmin->adm_id;
			$post['edit']['arena_time_start'] = strtotime($post['edit']['arena_time_start']);
			$post['edit']['arena_time_end'] = strtotime($post['edit']['arena_time_end']);
			if(isset($post['edit']['arena_code']) && $post['edit']['arena_code'] ==''){
					$post['edit']['arena_code'] = $this->sseo->seolink($post['edit']['arena_title']);
			}
			$post['edit']['arena_title_ascii'] = str_replace("-"," ",$this->sseo->seolink($post['edit']['arena_title']));
			$post['edit']['arena_time_update'] = time();
            if ($editID > 0) {
                $this->{$this->model}->update($editID, $this->{$this->model}->primaryKey, $post['edit']);
            }
			else{
				$post['edit']['arena_status'] = 0;
				$post['edit']['use_id_create'] = $this->madmin->adm_id;
				$editID = $this->{$this->model}->insert($post['edit']);
			}
            redirect($this->url_edit . $editID);
        }
		
		$data['edit'] = $this->{$this->model}->get($editID);
		$this->db->where('gins_type','arena');
		$data['game_keys'] = $this->mgameinstruction->gets($editID,'game_id');
		$this->theme_data["main"] = $this->view."/edit";
        $this->template->viewAdmin($this->theme_data, $data);
    }
	
	function delete($deleteID = 0){
		$this->check_permission();
		if($deleteID > 0){
			$this->{$this->model}->delete($deleteID);
		}
	}
	
	function upload_file($old_name = '', $newName = '') {
		$config = array();
		$config['upload_path'] = './'.$this->folder_upload."";
		$config['allowed_types'] = 'swf';
		$config['overwrite'] = true;
		if(!is_dir($this->folder_upload))
			mkdir($this->folder_upload,0777);
			
		if($old_name && isset($old_name)){
			unlink('./'.$old_name);
		}
		
		$this->load->library('upload');
		$this->upload->initialize($config);
		if ( !$this->upload->do_upload())
		{
			return false;
		}
		else
		{
			
			return array('upload_data' => $this->upload->data());
		}
	}
	
	function upload_my_file($arena_id = 0){
	
		$type = "";
		$arr_insert = array();
		require(APPPATH.'libraries/FileUpload.php');
		$game = $this->marena->get($arena_id,'arena_id');
		if(!$game){
			echo json_encode(array(
			'success' => false,
			'msg' => 'Game không tồn tại, vui lòng kiểm tra lại game.'
			));  
		}
		if(isset($_FILES['arena_thumb']) || isset($_GET['arena_thumb']))
		{
			$uploader = new FileUpload('arena_thumb');
			$type = "arena_thumb";
			$uploader->newFileName = $game->arena_code.'-'.$game->arena_id.'.'.$uploader->getExtension();
			$this->folder_upload = $this->folder_upload."thumb/";
		}
		else if(isset($_FILES['arena_thumb_large'])|| isset($_GET['arena_thumb_large']))
		{
			$uploader = new FileUpload('arena_thumb_large');
			$this->folder_upload = $this->folder_upload."thumb/";
			$uploader->newFileName = $game->arena_code.'-'.$game->arena_id.'-large'.'.'.$uploader->getExtension();
			$type = "arena_thumb_large";
		}
		else if(isset($_FILES['arena_file'])|| isset($_GET['arena_file']))
		{
			$uploader = new FileUpload('arena_file');
			$this->folder_upload = $this->folder_upload."data/";
			$type = "arena_file";
		}
		
		
		if(!is_dir($this->folder_upload))
			mkdir($this->folder_upload,0777);
		if($type =="")
			die("null");
		$uploader->allowedExtensions = array('jpg', 'jpeg', 'png', 'gif','swf');
		$uploader->sizeLimit = 21071520;
		//$uploader->sizeLimit = 1;
		//$uploader->newFileName = 'newFile.jpg';
		$result = $uploader->handleUpload('./'.$this->folder_upload);
		if (!$result) {
		echo json_encode(array(
		  'success' => false,
		  'msg' => $uploader->getErrorMsg()
		));    

		} else {
		
		$arr_insert[$type] = $this->folder_upload.''.$uploader->getFileName();
		$file_patch = base_url().$this->folder_upload.''.$uploader->getFileName();
		if($type =='arena_file') {
			$file_size = getimagesize($arr_insert[$type]);
			//width/height
			$arr_insert['arena_file_rate_height_width'] = $file_size[1]/$file_size[0];
			if($arr_insert['arena_file_rate_height_width'] >0.8)
				$arr_insert['arena_file_rate_height_width'] = 0.8;
		}
		else {
			$this->simage->cache($this->folder_upload.''.$uploader->getFileName());
			$file_patch = image_thumbnail($this->folder_upload.''.$uploader->getFileName(),'thumbnail');
			$file_patch = $file_patch."?v=".time();
		}
		$this->marena->update($arena_id,'arena_id',$arr_insert);
		
		echo json_encode(array(
			'success' => true,
			'file' => $file_patch,
			'rate' => @$arr_insert['arena_file_rate_height_width']
		 ));
		}
	}
	
	function upload_process(){
	
	if (isset($_SERVER['HTTP_ORIGIN'])) {
		header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
		header('Access-Control-Allow-Credentials: true');
		header('Access-Control-Max-Age: 86400');    // cache for 1 day
	}

	if (isset($_REQUEST['progresskey'])) 
		$status = apc_fetch('upload_'.$_REQUEST['progresskey']);
	else 
		exit(json_encode(array('success' => false)));

	$pct = 0;
	$size = 0;

	if (is_array($status)) {
		if (array_key_exists('total', $status) && array_key_exists('current', $status)) {
			if ($status['total'] > 0) {
				$pct = round( ( $status['current'] / $status['total']) * 100 );
				$size = round($status['total'] / 1024);
			}
		}
	}

	echo json_encode(array('success' => true, 'pct' => $pct, 'size' => $size));

	}
	function instruction($type='add_key',$game_id = 0){
		//$this->check_permission($game_id);
		$this->load->model("mgameinstruction");
		$key = $this->input->post("key");
		$value = $this->input->post("value");
		$prevalue = $this->input->post("prevalue");
		$result = array();
		$result['success'] = false;
		$result['key_key'] = $key;
		$result['key_value'] = $value;
		$result['key_pre_value'] = $prevalue;
		$result['html'] = '';
		if($type == 'add_key'){
			if($game_id >0 && $key && $value){
				$key_id = $this->mgameinstruction->insert(array(
				'game_id'=>$game_id,
				'gins_key'=>$key,
				'gins_description'=>$value,
				'gins_pre_description'=>$prevalue,
				'gins_type'=>'arena',
				));
				$html = '<select name="keykey[]" class="select2 input-key-key" id="" style="  ">';
				foreach($this->mgameinstruction->key_define as $k=>$v):
				$selected = ($k == $key)?' selected="selected" ':'';
				$html .='<option value="'.$k.'" '.$selected.'>'.$v.'</option>';
				endforeach; 
				$html.="</select> &nbsp;";
				if($key_id >0){
					$result['success'] = true;
					$result['key_id'] = $key_id;
					$result['key_key'] = $key;
					$result['key_value'] = $value;
					$result['key_pre_value'] = $prevalue;
					$result['html'] = $html;
				}
			}
			die( json_encode($result));
		}
		else if($type =='delete'){
			$key_id = $this->input->post("key_id");
			$this->db->where('game_id',$game_id);
			$this->db->where('gins_key',$key);
			$this->db->where('gins_type','arena');
			$this->mgameinstruction->delete($key_id ,'gins_id');
			$result['success'] = true;
			die( json_encode($result));
		}
		else if($type =='update'){
			$key_id = $this->input->post("key_id");
			$key_value= $this->input->post("value");
			$key_pre_value= $this->input->post("prevalue");
			$this->db->where('game_id',$game_id);
			$this->db->where('gins_type','arena');
			$this->mgameinstruction->update($key_id ,'gins_id',array(
			'gins_key'=>$key,
			'gins_description'=>$key_value,
			'gins_pre_description'=>$key_pre_value,
			));
			$result['success'] = true;
			die( json_encode($result));
		}	
		die( json_encode($result));
	}
	function ajax_process_change_status(){
		$this->init_process();
		$game_id = $this->input->post("game_id");
		$type = $this->input->post("type");
		$status = 0;
		if(!$this->mgame->permission('test_game'))
			die("Bạn không thực hiện được việc này");
		if($type =='accept')
			$status = -1;
		else
			$status = -3;
		$this->mgame->update($game_id,'game_id',array('game_status'=>$status));
	}
}
